import * as fs from "fs";
// import { getStat, getCurrentDirPath, isExistPath } from "../utils/fs";
// import { success, fail, ProxyMode } from "../utils/base";
import lockfile from "proper-lockfile";

let logMax = 4000;

export default defineEventHandler(async (event) => {
  // 获取请求参数
  const body = await readBody(event);
  // console.log("获取请求参数：", body);
  const pageFile = getCurrentDirPath("/public/log", "page-puv.json");
  // 用户对象文件
  const userFile = getCurrentDirPath("/public/log", "user-table.json");

  // 获取单例
  const instance = ProxyMode();
  // 防止并发过大
  try {
    instance.asyncNums++;
    if (instance.asyncNums > 1) {
      return success(`服务器繁忙${instance.asyncNums}`);
    }
  } catch (error) {
    console.log("服务端并发过大,已拦截", error);
  }
  /**
   * @description: 保存数据的时候文件,是否存在
   */
  const fileExistCall = async (
    writePath: string,
    filePath: string,
    call: any
  ) => {
    // 操作数据
    let isDir = await isExistPath(writePath);
    let isFile = await isExistPath(filePath!);
    /********* 文件保存出错的时候:需要删除文件 end *******/
    if (isDir && isFile) {
      const isLocked = await lockfile.check(filePath);
      if (isLocked) return success("文件已经枷锁,无法保存");
      return call && call(true);
    }
    // 不存在
    else {
      const isCreate = createDirectorySync(writePath);
      if (isCreate) {
        return call && call(false);
      } else {
        return fail("目录创建失败");
      }
    }
  };
  // 数据源拷贝,避免引用
  const pageObj = JSON.parse(JSON.stringify({ ...body }));
  const userObj = JSON.parse(JSON.stringify({ ...body.data.cusData }));
  // 1. 用户信息存储
  fileExistCall(userFile.writePath, userFile.filePath, async (val: boolean) => {
    const time = formatDate(new Date());

    delete userObj.from;
    delete userObj.to;
    delete userObj.avatar;
    delete userObj.mobile;

    if (val) {
      if (userObj && userObj != "undefined" && typeof userObj == "object") {
        // 1. 读取现有的 JSON 文件
        const jsonString = fs.readFileSync(userFile.filePath!, "utf8");
        const fileData = JSON.parse(jsonString);

        // 2. 添加记录
        if (userObj) {
          try {
            // 2.1 存在就不保存了
            const hasID = fileData.list.findIndex(
              (e: any) => e.id == userObj.id
            );
            if (hasID >= 0) return;
            // 2.2 插入数组
            fileData.list.push(userObj);
            // 2.3 将更新后的fileData , 写回文件
            const newJsonString = JSON.stringify(fileData, null, 2);
            //  加锁
            const release: any = await lockfile.lock(userFile.filePath);
            fs.writeFileSync(userFile.filePath!, newJsonString, "utf8");
            // 释放锁
            release();
          } catch (error) {
            console.log("fileExistCall user error:", error);
          }
        }
      }
    } else {
      const writeDate: any = {
        create: time,
        list: [],
      };
      // 添加一条数据
      if (userObj) {
        writeDate.list.push(userObj);
      }
      // 保存数据到文件
      await creatContentToPathSync(
        userFile.filePath!,
        JSON.stringify(writeDate, null, 2)
      );
    }
  });
  // 2. 页面 puv 保存
  return await fileExistCall(
    pageFile.writePath,
    pageFile.filePath,
    async (val: boolean) => {
      const time = formatDate(new Date());
      if (val) {
        if (pageObj && pageObj != "undefined" && typeof pageObj == "object") {
          // 1. 读取现有的 JSON 文件
          const jsonString = fs.readFileSync(pageFile.filePath!, "utf8");
          const fileData = JSON.parse(jsonString);

          // 1.1 防止数据过大 上限 logMax 条  超过这删除最老的 第 一条
          if (fileData.list.length > logMax) {
            fileData.list.shift();
          }

          // 2. 添加记录
          if (pageObj) {
            try {
              delete pageObj.record;
              delete pageObj.deviceInfo;
              const originalData = JSON.parse(JSON.stringify({ ...pageObj.data.cusData }));
              // const originalData = structuredClone(pageObj.data.cusData); // 最新的: 深拷贝
              delete originalData.avatar;
              delete originalData.mobile;
              pageObj.data.cusData = originalData;

              fileData.list.push(pageObj);
              // 将更新后的fileData , 写回文件
              const newJsonString = JSON.stringify(fileData, null, 2);
              //  加锁
              const release: any = await lockfile.lock(pageFile.filePath);
              fs.writeFileSync(pageFile.filePath!, newJsonString, "utf8");
              // 释放锁
              release();
              return success("添加成功");
            } catch (error) {
              return fail({ msg: "添加失败", error });
            }
          }
        } else {
          return fail("添加失败");
        }
      } else {
        const writeDate: any = {
          create: time,
          list: [],
        };
        // 添加一条数据
        if (pageObj) {
          writeDate.list.push(pageObj);
        }
        // 保存数据到文件
        const isOK = await creatContentToPathSync(
          pageFile.filePath!,
          JSON.stringify(writeDate, null, 2)
        );
        if (isOK === true) {
          return success("添加成功");
        } else {
          return fail("添加失败");
        }
      }
    }
  );
});
